package com.share.device.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.utils.StringUtils;
import com.share.device.domain.Cabinet;
import com.share.device.domain.Station;
import com.share.device.domain.StationLocation;
import com.share.device.mapper.CabinetMapper;
import com.share.device.mapper.RegionMapper;
import com.share.device.mapper.StationMapper;
import com.share.device.repository.StationLocationRepository;
import com.share.device.service.IRegionService;
import com.share.device.service.IStationService;
import jakarta.annotation.Resource;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author HSL
 * @version 1.0
 * @data 2025/8/29 14:28
 * @desc todo
 */
@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements IStationService {

    @Resource
    private StationMapper stationMapper;
    @Resource
    private CabinetMapper cabinetMapper;
    @Resource
    private RegionMapper regionMapper;
    @Resource
    private IRegionService iRegionService;
    @Resource
    private StationLocationRepository stationLocationRepository;

    @Override
    public List<Station> selectStationList(Station station) {
        LambdaQueryWrapper<Station> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(station.getName()), Station::getName, station.getName());
        wrapper.eq(ObjectUtil.isNotEmpty(station.getProvinceCode()), Station::getProvinceCode, station.getProvinceCode());
        wrapper.eq(ObjectUtil.isNotEmpty(station.getCityCode()), Station::getCityCode, station.getCityCode());
        wrapper.eq(ObjectUtil.isNotEmpty(station.getDistrictCode()), Station::getDistrictCode, station.getDistrictCode());
        wrapper.eq(ObjectUtil.isNotEmpty(station.getAddress()), Station::getAddress, station.getAddress());
        wrapper.eq(StringUtils.isNotEmpty(station.getHeadName()), Station::getHeadName, station.getHeadName());
        wrapper.eq(StringUtils.isNotEmpty(station.getHeadPhone()), Station::getHeadPhone, station.getHeadPhone());

        List<Station> stationList = stationMapper.selectList(wrapper);
        List<Long> cabinetIdList = stationList.stream().map(Station::getCabinetId).collect(Collectors.toList());

        Map<Long, String> cabIdAndNoMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(cabinetIdList)) {
            List<Cabinet> cabinetList = cabinetMapper.selectList(new LambdaQueryWrapper<Cabinet>().in(Cabinet::getId, cabinetIdList));
            cabIdAndNoMap = cabinetList.stream().collect(Collectors.toMap(Cabinet::getId, Cabinet::getCabinetNo));
        }
        // 不使用forEach 存在并发问题
        for (Station item : stationList) {

            item.setCabinetNo(cabIdAndNoMap.get(item.getCabinetId()));
        }
        return stationList;
    }

    @Override
    public int saveStation(Station station) {
        saveOrUpdateStation(station);

        //同步站点位置信息到MongoDB
        StationLocation stationLocation = new StationLocation();
        stationLocation.setId(ObjectId.get().toString());
        stationLocation.setStationId(station.getId());
        stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
        stationLocation.setCreateTime(new Date());
        stationLocationRepository.save(stationLocation);

        return stationMapper.insert(station);
    }

    private void saveOrUpdateStation(Station station) {
        String provinceName = iRegionService.getNameByCode(station.getProvinceCode());
        String cityName = iRegionService.getNameByCode(station.getCityCode());
        String districtName = iRegionService.getNameByCode(station.getDistrictCode());
        station.setFullAddress(provinceName + cityName + districtName + station.getAddress());
    }

    @Override
    public int updateStation(Station station) {
        saveOrUpdateStation(station);

        //同步站点位置信息到MongoDB
        StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
        stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
        stationLocationRepository.save(stationLocation);
        return stationMapper.updateById(station);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<?> list) {
        for (Object id : list) {
            stationLocationRepository.deleteByStationId(Long.parseLong(id.toString()));
        }
        return super.removeByIds(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int setData(Station station) {
        this.updateById(station);

        //更正柜机使用状态
        Cabinet cabinet = cabinetMapper.selectById(station.getCabinetId());
        cabinet.setStatus("1");
        return cabinetMapper.updateById(cabinet);
    }
}
